#!/usr/bin/env bash

# ----------------------------------------------------------------------
# Filename:   networkManager-syncookie.sh
# Version:    1.0
# Date:       2021/03/30
# Author:     laiyixin
# Email:      laiyixin@kylinos.com.cn
# History：
#             Version 1.0, 2021/03/30
# Function:   networkManager-syncookie - 开启syncookie功能
# Out:
#              0=> Success
#              1=> Fail
#              other=> TCONF
# ----------------------------------------------------------------------

## TODO: 使用ctrl+c退出
##
networkManagerOnCtrlC() {
    echo "正在优雅的退出..."
    networkManagerClean

    exit ${TFAIL}
}

## TODO: 用户界面
##
networkManagerUSAGE() {
    cat >&1 <<EOF
--------- networkManager-syncookie - 开启syncookie功能 ---------
EOF
}

## TODO : 执行前的初始化
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
networkManagerInit() {
    # 判断root用户
    if [ $(id -u) -ne 0 ]; then
        echo "Must use root ！"
        exit ${TCONF}
    fi

    # 信号捕获ctrl+c
    trap ' networkManagerOnCtrlC' INT

    networkManagerClean

}

## TODO : 执行进行时的方法
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
networkManagerTest() {
    if grep -RE "^\s*net.ipv4.tcp_syncookies" /etc/sysctl.d &>/dev/null; then
        while read -r filename; do
            sed -ri 's/(^\s*)net.ipv4.tcp_syncookies\s*=.*/\1net.ipv4.tcp_syncookies = 1/g' ${filename}
            networkManagerRetParse "update net.ipv4.tcp_syncookies = 1 to ${filename}"
        done < <(grep -RE "^\s*net.ipv4.tcp_syncookies" /etc/sysctl.d | awk -F: '{print $1}')
    else
        echo 'net.ipv4.tcp_syncookies = 1' >/etc/sysctl.d/tcp_syncookies.conf
        networkManagerRetParse "add net.ipv4.tcp_syncookies = 1 to /etc/sysctl.d/tcp_syncookies.conf"
        systemctl restart systemd-sysctl.service
        networkManagerRetParse "include net.ipv4.tcp_syncookies = 1 by /etc/sysctl.d/tcp_syncookies.conf"
    fi
}

## TODO : 执行收尾清除工作
##
networkManagerClean() {
    echo "Clean ..."

}

## TODO: 解析函数返回值
## In  : $1 => log
networkManagerRetParse() {
    local ret=$?
    local logstr=""

    if [ $# -eq 1 ]; then
        logstr="$1"
    fi

    if [ $ret -eq 0 ]; then
        echo "[pass] : ${logstr}"
    else
        echo "[fail] : ${logstr}"
        networkManagerClean
        exit ${TFAIL}
    fi
}

## TODO : Main
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
networkManagerMain() {
    networkManagerUSAGE

    networkManagerInit

    networkManagerTest

    networkManagerClean

    return ${TPASS}
}

networkManagerMain
exit $?
